package com.glp.controller;

import com.glp.common.constants.GlpConstants;
import com.glp.common.resp.ApiResult;
import com.glp.pojo.User;
import com.glp.services.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @GetMapping("add-user-view")
    public ModelAndView submitView() {
        ModelAndView mav = new ModelAndView("admin/add-user");
        return mav;
    }

    @PostMapping("addUser")
    @ResponseBody
    public ApiResult addUser(@RequestBody @Validated User user) {
        User curUser = (User) SecurityUtils.getSubject().getPrincipal();
        if (curUser.getRoleId() != GlpConstants.SYS_ROLE01) {
            return new ApiResult(500, "非法请求");
        }
        user.setCreateTime(new Date());
        User temp = userService.getUserByLoginName(user.getLoginName());
        if(ObjectUtils.isEmpty(temp)){
            userService.addUser(user);
        }else{
            return new ApiResult(500,user.getLoginName()+",此账号已存在！");
        }
        return new ApiResult();
    }

    @GetMapping("getAllUser")
    @ResponseBody
    public List<User> getAllUser() {
        User curUser = (User) SecurityUtils.getSubject().getPrincipal();
        if (curUser.getRoleId() != GlpConstants.SYS_ROLE01) {
            return null;
        }
        return userService.getAll();
    }

    @PostMapping("removeUser")
    @ResponseBody
    public ApiResult removeUser(@RequestParam Integer userId) {
        User curUser = (User) SecurityUtils.getSubject().getPrincipal();
        if (curUser.getRoleId() != GlpConstants.SYS_ROLE01) {
            return new ApiResult(500, "非法请求");
        }
        if (userId == GlpConstants.ANDROID_USER_ID) {
            return new ApiResult(500, "无法删除！");
        }
        int count = userService.removeUser(userId);
        return new ApiResult();
    }
}
